# -*- coding: utf-8 -*-
import wsgiref.handlers
from google.appengine.ext import webapp
import sys, time, uuid
import os
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from xmw import tianya
from xmw.tianya.bot import *
import xmw
from xmw.tianya import error_tianya

class MainPage(xmw.RequestHandler):
  def get(self):
    if  self.request.GET.has_key('url'):
        url = self.request.GET['url']
        
        q = Bot_Thread.all()
        q.filter("page_url =", url)
        q.filter("is_readed =", False)        
        thread = q.get()   
            
        if (thread is None):
            #没有找到
            e = error_tianya.THREAD_NOT_EXIST("fresh thread with url :%s not found!" % url)
            self.render_error(e)
        else:
            #找到
            template_values = {
                               "thread":thread
                               }
            path = os.path.join(os.path.dirname(__file__), 'template/thread.html')
            self.response.out.write(template.render(path, template_values))
            thread.is_readed=True
            thread.put()
        
    else:
        e = error_tianya.ARGUMENT_FAULT("URI:query_thread needs parameter thread_id.    /query_thread?url=XXXX")
        self.render_error(e)

def main():
    import global_setting
    
    application = webapp.WSGIApplication(
                                       [('/read_thread', MainPage)],
                                       debug=global_setting.is_debug())                                       
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
    main()
